<template>
  <div class="contanier">
    <div class="home">
      <div class="header">
        <el-carousel height="80vh" motion-blur="true" interval="5000" trigger="click">
          <el-carousel-item v-for="(item, index) in showdata" :key="index" @click="goto(item)">
            <div class="time">{{ item.date }}</div>
            <div class="title">{{ item.title }}</div>
            <img :src="item.img" />
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <div class="tab">
      <div class="calendar">
        <el-calendar v-model="value" style="margin-bottom: 20px">
          <template #header="{ date }">
            <span>{{ date }}</span>
          </template></el-calendar>
        <div id="he-plugin-standard"></div>
      </div>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="热门游记" name="first" class="pane">
          <div class="box" v-for="(item, index) in showdata" :key="index">
            <div class="right">
              <img :src="item.img" />
            </div>
            <div class="left">
              <el-link class="one" href="" target="_blank" @click="goclick(item)">{{ item.title }}</el-link>

              <div class="two">{{ item.description }}</div>
              <div class="buttom">
                <div class="author">
                  By
                  <img
                    src="https://img1.baidu.com/it/u=4256350010,1509363888&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400" />
                  {{ item.author }}
                </div>
                <div class="like">喜爱度：{{ item.averageLikeValue }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="最新发表" name="second" class="pane">
          <div class="box" v-for="(item, index) in timedata" :key="index">
            <div class="right">
              <img :src="item.img" />
            </div>
            <div class="left">
              <el-link class="one" href="" target="_blank" @click="goclick(item)">{{ item.title }}</el-link>

              <div class="two">{{ item.description }}</div>
              <div class="buttom">
                <div class="author">
                  By
                  <img
                    src="https://img1.baidu.com/it/u=4256350010,1509363888&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400" />
                  {{ item.author }}
                </div>
                <div class="like">喜爱度：{{ item.averageLikeValue }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type {  strategyObject, strategyRespnseData } from '@/api/strategy/type'
import { getstrategydata } from '../../api/strategy/index'
import { ref, onMounted } from 'vue'
import { usestrategyStore } from '../..//stores/strategy'
const strategyStore = usestrategyStore()

const value = ref(new Date())
let showdata = ref<strategyObject[]>([])
let timedata = ref<strategyObject[]>([])
const showHtml = (str: string) => {
  if (str.indexOf('\\t') !== -1) {
    console.log('String contains a tab character.')
  }

  return str.replace(/\\t/g, '\u3000\u3000').replace(/\\\t/g, '\u3000\u3000')
}
const initdata = async () => {
  let result: strategyRespnseData = await getstrategydata()

  if (result.status == 0) {
    for (let i = 0; i < result.data.length; i++) {
      result.data[i].like = JSON.parse(result.data[i].like as string)
      result.data[i].tag = JSON.parse(result.data[i].tag)
      result.data[i].collect = JSON.parse(result.data[i].collect as string)
      result.data[i].content = showHtml(result.data[i].content)
      let description = result.data[i].content
      description = description
        .replace(/(\n)/g, '')
        .replace(/(\t)/g, '')
        .replace(/(\r)/g, '')
        .replace(/<\/?[^>]*>/g, '')
        .replace(/\s*/g, '')
      result.data[i].description = description
    }

    // 遍历数组A中的每个对象B
    result.data.forEach((item) => {
      // 初始化变量来保存value的总和
      let sum = 0
      // 初始化变量来保存like数组的长度
      let length = 0

      // 遍历对象B中的like数组
      if (Array.isArray(item.like)) {
        item.like.forEach((likeItem: any) => {
          console.log(likeItem);
          
          // 累加value的值
          sum += likeItem.value;
          // 增加like数组的长度
          length++;
        });
      }

      // 检查like数组是否有元素，以避免除以0的错误
      if (length > 0) {
        // 计算平均值并保存在对象B中
        item.averageLikeValue = sum / length
      } else {
        item.averageLikeValue = 0
      }
    })
    strategyStore.modifystrategydatadata(result.data)

    showdata.value = [...result.data]
    timedata.value = [...result.data]

    // 使用 sort 方法，根据 averageLikeValue 属性从高到低排序
    showdata.value.sort((a: strategyObject, b: strategyObject) => (b.averageLikeValue as number) - (a.averageLikeValue as number))
    timedata.value.sort((a: strategyObject, b: strategyObject): number => {
      // 将日期字符串转换为日期对象并获取时间戳进行比较
      const dateA = new Date(a.date).getTime();
      const dateB = new Date(b.date).getTime();

      // 按日期的降序排列
      return dateB - dateA;
    });
    // 或者要复制前五个元素到新数组，可以这样：
    showdata.value = showdata.value.slice(0, 5)
    timedata.value = timedata.value.slice(0, 5)
  }
}


const goclick = (item: strategyObject) => {
  const encodedObject = encodeURIComponent(JSON.stringify(item))

  let routerData = $router.resolve({
    path: '/astrategy',
    query: {
      item: encodedObject
    }
  })
  window.open(routerData.href, '_blank')
}
import { useRouter } from 'vue-router'
let $router = useRouter()
const goto = (item: strategyObject) => {
  const encodedObject = encodeURIComponent(JSON.stringify(item))

  let routerData = $router.resolve({
    path: '/astrategy',
    query: {
      item: encodedObject
    }
  })
  window.open(routerData.href, '_blank')
}

import type { TabsPaneContext } from 'element-plus'

const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
declare global {
  interface Window {
    WIDGET: any; // 可以根据实际需要替换成具体的类型
  }
}
// 在组件挂载后发起请求
onMounted(() => {
  console.log(111);
  
  //和风天气插件调用
  window.WIDGET = {
    CONFIG: {
      layout: '2',
      width: 300,
      height: 270,
      background: '2',
      dataColor: '000000',
      aqiColor: 'FFFFFF',
      key: 'a3f65772bd4143aca2350bad91febb4f'
    }
  }
    ; (function (d) {
      var c = d.createElement('link')
      c.rel = 'stylesheet'
      c.href =
        'https://widget.qweather.net/standard/static/css/he-standard.css?v=1.4.0'
      var s = d.createElement('script')
      s.src =
        'https://widget.qweather.net/standard/static/js/he-standard.js?v=1.4.0'
      var sn = d.getElementsByTagName('script')[0]
      sn?.parentNode?.insertBefore(c, sn);
  sn?.parentNode?.insertBefore(s, sn);
    })(document)

  initdata()
})
</script>

<style scoped>
.contanier {
  width: 100%;
  background-color: white;
}

.home {
  width: 100%;
  display: flex;
  justify-content: center;

  .header {
    width: 100%;
    position: relative;

    .time {
      font-size: 30px;
      font-weight: 800;
      position: absolute;
      left: 25%;
      top: 20%;
    }

    .title {
      font-size: 30px;
      font-weight: 800;
      position: absolute;
      left: 25%;
      top: 30%;
    }

    img {
      width: 100%;
      height: 100%
    }
  }
}

.tab {
  /* margin-left: 28%; */
  color: #ffc952;
  margin-top: 10px;
  display: flex;
  height: 100%;

  .demo-tabs {
    width: 50%;
    margin-left: 5%;
  }

  .pane {
    color: #ffc952;
  }

  .box {
    display: flex;
    width: 100%;

    border-radius: 15px;
    margin-bottom: 50px;

    .left {
      width: 65%;
      height: 100%;

      .one {
        font-size: 25px;
      }

      .two {
        margin: 20px 0px;
        color: #666;
        font-size: 14px;
        width: 100%;
        height: 60px;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        /* 指定显示的行数 */
        -webkit-box-orient: vertical;
        text-overflow: ellipsis;
        line-height: 1.5;
      }
    }

    .right {
      margin-left: 20px;
      margin-right: 20px;

      img {
        width: 170px;
        height: 150px;
      }
    }

    .buttom {
      display: flex;
      color: #ffc952;
      align-content: center;
      justify-content: space-between;

      .author {
        display: flex;
      }

      .like {
        font-size: 15px;
      }

      img {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        margin: 0 5px;
      }
    }
  }
}

.calendar {
  width: 300px;
  height: 200px;
  margin-left: 15%;
  position: sticky;
  top: 5%;
  z-index: 100;
  /* 确保子盒子C在父盒子A之上 */
}

div/deep/.el-tabs__item {
  font-size: 25px !important;
  height: 50px;
  color: #000000 !important;
}

div/deep/.el-tabs__item.is-active {
  color: #ffc952 !important;
  font-size: 25px;
}

div/deep/.el-tabs__active-bar {
  background-color: #ffc952 !important;
}

div/deep/.el-calendar__body {
  padding: 0;
}

div/deep/ .el-calendar-table .el-calendar-day {
  height: 30px;
  width: 35px;
}
</style>
